package org.alwayssuper.protocol.commons.transform.realtimev2016;

import org.alwayssuper.protostar.annotation.Field;
import lombok.Data;
import lombok.ToString;
import lombok.experimental.Accessors;

/**
 * 2016版发动机数据格式 (0x04)
 * 参考GB/T 32960.3-2016标准表13
 * @author alwaysSuper
 */
@ToString
@Data
@Accessors(chain = true)
public class EngineData {
    @Field(length = 1, desc = "发动机状态:0x01:启动状态;0x02:关闭状态;0xFE:异常;0xFF:无效")
    private int engineStatus;
    
    @Field(length = 2, desc = "曲轴转速:0~60000r/min,精度1r/min,0xFFFF无效")
    private int crankshaftSpeed;
    
    @Field(length = 2, desc = "燃料消耗率:0~600L/100km,精度0.01L/100km,0xFFFF无效")
    private int fuelConsumptionRate;
    
    // =========================== 传输值与真实值转换方法 ===========================
    
    /**
     * 获取曲轴转速值 (r/min)
     * 传输值范围: 0~60000, 表示 0r/min~60000r/min, 精度 1r/min
     * 0xFFFE: 异常, 0xFFFF: 无效
     */
    public double getCrankshaftSpeed() {
        if (crankshaftSpeed == 0xFFFE || crankshaftSpeed == 0xFFFF) {
            return Double.NaN;
        }
        return crankshaftSpeed;
    }
    
    /**
     * 设置曲轴转速值 (r/min)
     * 值范围: 0r/min~60000r/min
     */
    public void setCrankshaftSpeed(double crankshaftSpeed) {
        if (Double.isNaN(crankshaftSpeed) || crankshaftSpeed < 0 || crankshaftSpeed > 60000) {
            this.crankshaftSpeed = 0xFFFF; // 无效
        } else {
            this.crankshaftSpeed = (int) Math.round(crankshaftSpeed);
        }
    }
    
    /**
     * 获取燃料消耗率值 (L/100km)
     * 传输值范围: 0~60000, 表示 0L/100km~600L/100km, 精度 0.01L/100km
     * 0xFFFE: 异常, 0xFFFF: 无效
     */
    public double getFuelConsumptionRate() {
        if (fuelConsumptionRate == 0xFFFE || fuelConsumptionRate == 0xFFFF) {
            return Double.NaN;
        }
        return fuelConsumptionRate * 0.01;
    }
    
    /**
     * 设置燃料消耗率值 (L/100km)
     * 值范围: 0L/100km~600L/100km
     */
    public void setFuelConsumptionRate(double fuelConsumptionRate) {
        if (Double.isNaN(fuelConsumptionRate) || fuelConsumptionRate < 0 || fuelConsumptionRate > 600.0) {
            this.fuelConsumptionRate = 0xFFFF; // 无效
        } else {
            this.fuelConsumptionRate = (int) Math.round(fuelConsumptionRate * 100);
        }
    }
    
    /**
     * 检查发动机状态是否异常
     */
    public boolean isEngineStatusAbnormal() {
        return engineStatus == 0xFE;
    }
    
    /**
     * 检查发动机状态是否无效
     */
    public boolean isEngineStatusInvalid() {
        return engineStatus == 0xFF;
    }
    
    /**
     * 检查曲轴转速是否异常
     */
    public boolean isCrankshaftSpeedAbnormal() {
        return crankshaftSpeed == 0xFFFE;
    }
    
    /**
     * 检查曲轴转速是否无效
     */
    public boolean isCrankshaftSpeedInvalid() {
        return crankshaftSpeed == 0xFFFF;
    }
}